package com.mengniu.commerce.collect.service.impl.member;


import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mengniu.commerce.collect.model.member.QueryMemberParam;
import com.mengniu.commerce.collect.service.WmMemberService;
import com.mengniu.commerce.collect.third.request.IWeiMengMemberRequest;
import com.mengniu.commerce.collect.third.response.member.MemberInfoResponse;
import com.mengniu.commerce.collect.third.response.member.MemberListResponse;
import com.mengniu.commerce.collect.third.response.member.MemberResponse;
import com.mengniu.commerce.collect.util.RestTemplateUtil;
import com.mengniu.commerce.common.core.enums.SourceEnum;
import com.mengniu.commerce.common.core.utils.DateUtils;
import com.mengniu.commerce.common.core.utils.StringUtils;
import com.mengniu.commerce.sync.api.RemoteMemberService;
import com.mengniu.commerce.sync.api.domain.MemberInsertModel;
import com.mengniu.commerce.sync.api.domain.MemberModifyModel;
import com.mengniu.commerce.sync.api.domain.MemberRegisterModel;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * 参数配置 服务层实现
 *
 * @author yz_sm
 */
@Service
public class WmMemberServiceImpl implements WmMemberService
{

    public static final String MN_QY_MEMBER = "MN_QY_MEMBER";
    public static final String API_VERSION = "v2.0";

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    @Resource
    private RemoteMemberService remoteMemberService;

    @Autowired
    private IWeiMengMemberRequest weiMengMemberRequest;

    /***
    * @Description: 会员注册
    * @Param: []
    * @return: void
    * @Author: zfw
    * @Date: 2023/12/3
    * @Date: 17:23
    */
    @Override
    public void createMemberByMsg(Long bosId,List<String> list) {
        List<MemberRegisterModel> regList = new ArrayList<>();
        //查询会员
        String token = restTemplateUtil.getToken(bosId);
        //循环查询用户详情
        List<String> typeList = Stream.of("1", "2", "3", "4").collect(Collectors.toList());
        MemberInfoResponse memberInfo = weiMengMemberRequest.getMemberInfoById(list,typeList,token);
        if (!CollectionUtils.isEmpty(memberInfo.getData().getUserBaseInfoList())) {
            //循环用户基本信息
            for (MemberInfoResponse.UserBaseInfo user : memberInfo.getData().getUserBaseInfoList()) {
                //跳过手机号和姓名为空的数据
                if (ObjectUtils.isEmpty(user.getName()) || ObjectUtils.isEmpty(user.getPhone())) {
                    continue;
                }
                regList.add(this.convertToMemberRegisterModel(user));
            }
        }
        regList.forEach(item ->{
            remoteMemberService.memberRegister(item, SourceEnum.WM.getSource(),item.getThirdId());
        });

    }

    /***
    * @Description: 存量会员创建
    * @Param: [bosId]
    * @return: void
    * @Author: zfw
    * @Date: 2023/12/3
    * @Date: 17:42
    */
    @Override
    public void createStockMember(Long bosId) {
        List<MemberInsertModel> list = new ArrayList<>();
        //查询会员
        String token = restTemplateUtil.getToken(bosId);
        List<MemberListResponse> listWid = this.getWeiMengUserList();
        // 获取所有的wid属性
        List<String> wList = listWid.stream()
                .map(MemberListResponse::getWid)
                .collect(Collectors.toList());
        //防止listWid较大,进行拆分
        int batchSize = 20;
        Map<Integer, List<String>> partitionedList = wList.stream()
                .collect(Collectors.groupingBy(s -> (list.indexOf(s) / batchSize)));
        // 打印拆分后的结果
        partitionedList.forEach((k, v) ->{
            //循环查询用户详情
            List<String> typeList = Stream.of("1", "2", "3", "4").collect(Collectors.toList());
            MemberInfoResponse memberInfo = weiMengMemberRequest.getMemberInfoById(v,typeList,token);
            if (!CollectionUtils.isEmpty(memberInfo.getData().getUserBaseInfoList())) {
                //循环用户基本信息
                for (MemberInfoResponse.UserBaseInfo user : memberInfo.getData().getUserBaseInfoList()) {
                    //跳过手机号和姓名为空的数据
                    if (ObjectUtils.isEmpty(user.getName()) || ObjectUtils.isEmpty(user.getPhone())) {
                        continue;
                    }
                    list.add(this.convert(user));
                }
            }
        });
        System.out.println(JSONObject.toJSONString(list));
        remoteMemberService.memberInsert(list, SourceEnum.WM.getSource());
    }

    /**
     * 获取用户WID列表  todo 替换bosId
     * @return
     */
    @Override
    public List<MemberListResponse> getWeiMengUserList() {
        List<MemberListResponse> list = new ArrayList<>();
        //查询会员
        String token = restTemplateUtil.getToken(4001169348805L);
        QueryMemberParam queryMemberParam = new  QueryMemberParam();
        queryMemberParam.setPageNum(1);
        queryMemberParam.setPageSize(10);
        //首先获取会员列表总数
        MemberResponse memberResponse = weiMengMemberRequest.getMemberList(queryMemberParam,token);
        //会员总数
        int totalCount = memberResponse.getData().getTotalSize();
        int pageSize = 20;
        int pageTotal = (int) Math.ceil(totalCount * 1.0 / pageSize);
        for(int i=1;i<=pageTotal;i++){
            queryMemberParam.setPageNum(i);
            queryMemberParam.setPageSize(pageSize);
            //调用蒙牛接口查询会员
            MemberResponse memberList = weiMengMemberRequest.getMemberList(queryMemberParam,token);
            if (!StringUtils.isEmpty(memberList.getData().getResult())){
                List<MemberListResponse> listWid = JsonToList(memberList.getData().getResult());
                list.addAll(listWid);
            }
        }
        return list;
    }

    /***
    * @Description: 更新用户
    * @Param: []
    * @return: void
    * @Author: zfw
    * @Date: 2023/12/3
    * @Date: 15:49
    */
    @Override
    public void modifyMemberByMessage(Long bosId,List<String> list) {
        //查询会员
        String token = restTemplateUtil.getToken(bosId);
        //循环查询用户详情
        List<String> typeList = Stream.of("1", "2", "3", "4").collect(Collectors.toList());
        MemberInfoResponse memberInfo = weiMengMemberRequest.getMemberInfoById(list,typeList,token);
        if (!CollectionUtils.isEmpty(memberInfo.getData().getUserBaseInfoList())) {
            //循环用户基本信息
            for (MemberInfoResponse.UserBaseInfo user : memberInfo.getData().getUserBaseInfoList()) {
                //跳过手机号和姓名为空的数据
                if (ObjectUtils.isEmpty(user.getName()) || ObjectUtils.isEmpty(user.getPhone())) {
                    continue;
                }
                remoteMemberService.memberModify(this.convertToMemberModifyModel(user),SourceEnum.WM.getSource());
            }
        }
    }

    /**
     * 将微盟数据转换为蒙牛需要的数据
     * @param info
     * @return
     */
    private MemberInsertModel convert(MemberInfoResponse.UserBaseInfo info) {
        MemberInsertModel memberInsertModel = new MemberInsertModel();
        //TODO  RetryDTO
//        memberInsertModel.setSource("蒙牛中间件");
        memberInsertModel.setUserId(info.getWid()+"");
        memberInsertModel.setMemberRegisterModel(convertToMemberRegisterModel(info));
        return memberInsertModel;
    }

    /**
     * 将微盟数据转换为蒙牛需要的数据
     * @param info
     * @return
     */
    private MemberRegisterModel convertToMemberRegisterModel(MemberInfoResponse.UserBaseInfo info) {
        MemberRegisterModel memberInfo = new MemberRegisterModel();
        //组装数据
        memberInfo.setOperationUnitType(MN_QY_MEMBER);
        memberInfo.setApiVersion(API_VERSION);
        memberInfo.setName(info.getName());
        memberInfo.setBirthday(ObjectUtils.isEmpty(info.getBirthday()) ? null : DateUtils.stampToDate(info.getBirthday()));
        memberInfo.setSex(info.getGender());
        memberInfo.setMobile(info.getPhone());
        memberInfo.setOpenId(info.getWid()+"");
        memberInfo.setUnionId(info.getWid()+"");
        memberInfo.setNickName(info.getNickname());
        memberInfo.setAnniversarySource(ObjectUtils.isEmpty(info.getSourceChannel().get(0))?null:info.getSourceChannel().get(0).toString());
        memberInfo.setAnniversaryDate(ObjectUtils.isEmpty(info.getBecomeMemberTime()) ? "2023-12-01" :DateUtils.stampToDate(info.getBecomeMemberTime()));
        memberInfo.setMembershipAgreementTime(ObjectUtils.isEmpty(info.getBecomeMemberTime()) ? "2023-12-01" :DateUtils.stampToDate(info.getBecomeMemberTime()));
        memberInfo.setMembershipAgreementVersion("v1.0");
        /*memberInfo.setProvince("Beijing");
        memberInfo.setCity("Shanghai");*/
        memberInfo.setAvatar(info.getAvatarUrl());
        memberInfo.setActivity("蒙牛中间件");
        //memberInfo.setFromPage("page1");
        memberInfo.setRegtime(DateUtils.stampToDate(info.getBelongVidBindTime()));
        memberInfo.setThirdId(info.getWid()+"");
        memberInfo.setSourceBrand(MN_QY_MEMBER);
        memberInfo.setWithBenefit(true);
        //memberInfo.setSourcePromoterId("promoter123");
        //memberInfo.setSourcePromoterName("Alice");
        memberInfo.setSourceShopId(info.getBelongVid()+"");
        memberInfo.setSourceShopName(info.getBelongVid()+"");
        memberInfo.setEducation(info.getEducation()+"");
        memberInfo.setOccupation(info.getIndustry());
        //memberInfo.setMaritalStatus("1");
        //memberInfo.setChildrenStatus("Has children");
        return memberInfo;
    }

    /***
    * @Description: 封装修改会员参数
    * @Param: []
    * @return: com.mengniu.commerce.sync.api.domain.MemberModifyModel
    * @Author: zfw
    * @Date: 2023/12/3
    * @Date: 17:46
    */
    public MemberModifyModel convertToMemberModifyModel(MemberInfoResponse.UserBaseInfo info){
        MemberModifyModel memberModifyModel = new MemberModifyModel();
        memberModifyModel.setOperationUnitType(MN_QY_MEMBER);
        memberModifyModel.setApiVersion(API_VERSION);
        memberModifyModel.setName(info.getName());
        memberModifyModel.setBirthday(ObjectUtils.isEmpty(info.getBirthday()) ? null : DateUtils.stampToDate(info.getBirthday()));
        memberModifyModel.setSex(info.getGender());
        memberModifyModel.setMobile(info.getPhone());
        memberModifyModel.setOpenId(info.getWid()+"");
        memberModifyModel.setUnionId(info.getWid()+"");
        memberModifyModel.setNickName(info.getNickname());
        memberModifyModel.setProvince("Beijing");
        memberModifyModel.setCity("Shanghai");
        memberModifyModel.setAvatar(info.getAvatarUrl());
        return memberModifyModel;
    }

    /**
     * 将Json 转为List todo 后期考虑做成公共类
     * @param json
     * @return
     */
    public List<MemberListResponse> JsonToList (String json) {
        ObjectMapper objectMapper = new ObjectMapper();
        List<MemberListResponse> list = new ArrayList<>();
            try {
                JsonNode jsonNode = objectMapper.readTree(json);
                for (JsonNode node : jsonNode) {
                    //手机号不为null 再返回
                    if (!ObjectUtils.isEmpty(node.get("phone").textValue())){
                        MemberListResponse memberListResponse = new MemberListResponse();
                        memberListResponse.setWid(node.get("wid").textValue());
                        memberListResponse.setPhone(node.get("phone").textValue());
                        list.add(memberListResponse);
                    }

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return list;
        }


}
